package org.sapfeed.main;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class SapFeedServlet
 */
@WebServlet(urlPatterns = { "/PubModel","/Logout","/GetPubDetails","/GetTotalPublished","/PublishInfo","/SapFeedServlet","/Logout","/GetName", "/GetData", "/Unsubscribe", "/Subscribe","/GetTotal", "/AddData","/Login","/GetPubData","/Signup","/Test","/ConsumptionInfo"})

public class SapFeedServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private SQLDataBase dbConnection;
    private boolean loggedIn = false;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SapFeedServlet() {
        super();
        dbConnection = new SQLDataBase();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String command = request.getRequestURI();
		Gson gson = new Gson();
		PrintWriter out = response.getWriter();
		String error;
		String json;
		if(command.endsWith("/GetData") && loggedIn) {
			response.setContentType("application/json");
			//Get Lists from the SQL database and forward them to jsp page
			List<DataSet > dataList = dbConnection.getDataSets();
			List<Integer > userList = dbConnection.getUserDataSets();
			List sets = new ArrayList() ;
			sets.add(dataList);
			sets.add(userList);
			json = gson.toJson(sets);
			out.println(json);
			return;
			
		} else if (command.endsWith("/ConsumptionInfo")&& loggedIn) {
			//TODO: subscribe to the data set
			String dataSet = request.getParameter("dataSet");
			int numberOfMessages = dbConnection.getUserConsumption(dataSet);
			json = gson.toJson(numberOfMessages);
			out.println(json);
			return;
			
		} else if (command.endsWith("/GetName")&& loggedIn) {
			//TODO: subscribe to the data set
			String userID = request.getParameter("userID");
			String username = dbConnection.getUserName(userID);
			json = gson.toJson(username);
			out.println(json);
			return;
			
		} else if (command.endsWith("/PubModel")&& loggedIn) {
			//TODO: subscribe to the data set
			String dataSet = request.getParameter("dataSet");
			String pubModel = dbConnection.getPubModel(dataSet);
			json = gson.toJson(pubModel);
			out.println(json);
			return;
			
		} else if (command.endsWith("/GetPubDetails")&& loggedIn) {
			//TODO: subscribe to the data set
			String dataSet = request.getParameter("dataSet");
			List info = dbConnection.getPublisherNameAndSubscriberNumber(dataSet);
			json = gson.toJson(info);
			out.println(json);
			return;
			
		} else if (command.endsWith("/PublishInfo")&& loggedIn) {
			//TODO: subscribe to the data set
			String dataSet = request.getParameter("dataSet");
			int numberOfMessages = dbConnection.getPublishConsumption(dataSet);
			json = gson.toJson(numberOfMessages);
			out.println(json);
			return;
			
		} else if (command.endsWith("/Subscribe")&& loggedIn) {
			//TODO: subscribe to the data set
			String dataSet = request.getParameter("dataSet");
			
			if(dbConnection.subscribeDataSet(dataSet)) {
				error = "false";
				//request.setAttribute("error", "false" );
			} else {
				error = "true";
				//request.setAttribute("error", "true" );
			}
			json = gson.toJson(error);
			out.println(json);
			return;
			
		} else if (command.endsWith("/Unsubscribe")&& loggedIn) {
			//TODO: unsubscribe to the data set
			String dataSet = request.getParameter("dataSet");
			
			if(dbConnection.unsubscribeDataSet(dataSet)) {
				error = "false";
				//	request.setAttribute("error", "false" );
			} else {
				error = "true";
			//	request.setAttribute("error", "true" );
			}
			json = gson.toJson(error);
			out.println(json);
			return;
		} else if (command.endsWith("/AddData")&& loggedIn) {
			//TODO: unsubscribe to the data set
			int ds_id;
			String dataSet = request.getParameter("dataSet");
			String dataSetDescription = request.getParameter("dataSetDesc");
			String model =request.getParameter("pricing");
			ds_id = dbConnection.addNewDataSet(dataSet,dataSetDescription, model);
			if(ds_id != -1) {
				error = "false";
				//	request.setAttribute("error", "false" );
			} else {
				error = "true";
			//	request.setAttribute("error", "true" );
			}
			json = gson.toJson(ds_id);
			out.println(json);
			return;
		} else if (command.endsWith("/GetTotal")&& loggedIn) {
			//TODO: unsubscribe to the data set
			String dataSet = request.getParameter("dataSet");
			int numberOfMessages = dbConnection.getTotalMessages(dataSet);
			json = gson.toJson(numberOfMessages);
			out.println(json);
			return;
		} else if (command.endsWith("/GetTotalPublished")&& loggedIn) {
			//TODO: unsubscribe to the data set
			String dataSet = request.getParameter("dataSet");
			int numberOfMessages = dbConnection.getTotalPublished(dataSet);
			json = gson.toJson(numberOfMessages);
			out.println(json);
			return;
		} else if (command.endsWith("/Login")) {
			//TODO: Login in to the admin page
			String userid = request.getParameter("username");
			String password = request.getParameter("password");
			try {
				if(dbConnection.getUser(userid, password).equals(" Login Successful ")) {
					loggedIn = true;
					error = "false";
				//	request.setAttribute("error", "false" );
				} else {
					error = "true";
				//	request.setAttribute("error", "true" );
				}
				json = gson.toJson(error);
				out.println(json);
				return;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else if (command.endsWith("/GetPubData")&& loggedIn) {
			List pubList = dbConnection.getPublishers();
			json = gson.toJson(pubList);
			out.println(json);
			return;
		} else if (command.endsWith("/Logout")&& loggedIn) {
			loggedIn = false;
			json = gson.toJson("You have successfully logged out");
			out.println(json);
			return;
		} else if (command.endsWith("/Signup")) {
			String username = request.getParameter("username");
			String password = request.getParameter("password");
			String message = dbConnection.addUser(username, password);
			json = gson.toJson(message);
			out.println(json);
			return;
		} else if (command.endsWith("/Test")) {
			
			int [] array = {1,2,3,4,5};
			int [] array2 = {1,2,3,4,5};
			response.setContentType("application/json");
			JsonArray jsarray = new JsonArray();
			JsonObject obj = new JsonObject();

			
			json = gson.toJson(array);
			out.println(json);
			return;
		} else {
			error = "true";
		//	request.setAttribute("error", "true" );
			json = gson.toJson(error);
			out.println(json);
			return;
		}
		request.getRequestDispatcher("/test.html").forward(request, response);
		System.out.println("forwarded.");
	//	response.sendRedirect("/SAPFeed/admin.jsp");
	}

}
